<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">楼宇名称：</span>
      <el-input v-model="dataParams.name" clearable placeholder="请输入内容" class="search-main" />
      <el-button type="primary" class="search-btn" @click="serchList">查询</el-button>
    </div>

    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button type="primary" @click="showDialog=true">添加楼宇</el-button>
      <el-button type="primary" @click="exportToExcel">导出Excel</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="tableData">
        <el-table-column type="index" label="序号" />
        <el-table-column label="楼宇名称" prop="name" />
        <el-table-column label="层数" prop="floors" />
        <el-table-column label="在管面积(m²)" prop="area" />
        <el-table-column label="物业费(元/m²)" prop="propertyFeePrice" />
        <el-table-column label="状态" prop="status" :formatter="formatStatus" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="{row}">
            <el-button size="mini" type="text" @click="editBuilding(row.id)">编辑</el-button>
            <el-button size="mini" type="text" @click="delBuliding(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        layout="total, prev,sizes, pager, next"
        :page-size="dataParams.pageSize"
        :total="total"
        :page-sizes="[2, 5,10,20]"
        @current-change="pageChage"
        @size-change="handleSizeChange"
      />
    </div>
    <!-- 添加楼宇 -->
    <!-- 表单接口 -->
    <el-dialog
      :title="title"
      width="580px"
      :visible.sync="showDialog"
    >
      <div class="form-container">
        <el-form ref="addForm" :model="addForm" :rules="addFormRules">
          <el-form-item label="楼宇名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>
          <el-form-item label="楼宇层数" prop="floors">
            <el-input v-model="addForm.floors" />
          </el-form-item>
          <el-form-item label="在管面积" prop="area">
            <el-input v-model="addForm.area" />
          </el-form-item>
          <el-form-item label="物业费" prop="propertyFeePrice">
            <el-input v-model="addForm.propertyFeePrice" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button size="mini" @click="showDialog=false">取 消</el-button>
        <el-button size="mini" type="primary" @click="confirmAdd">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { createBuildingListAPI, deleteBuildingAPI, editBuildingListAPI, getBuildingDetailAPI, getBuildingListAPI } from '@/api/building'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  data() {
    return {
      dataParams: {
        name: '',
        page: 1,
        pageSize: 10,
        floors: '',
        area: '',
        propertyFeePrice: '',
        status: ''
      },
      addForm: {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入楼宇层数', trigger: 'blur' }
        ],
        area: [
          { required: true, message: '请输入楼宇面积', trigger: 'blur' }
        ],
        propertyFeePrice: [
          { required: true, message: '请输入楼宇物业费', trigger: 'blur' }
        ]
      },
      tableData: [],
      total: 0,
      showDialog: false,
      title: '添加楼宇'
    }
  },
  created() {
    this.getBuildingList()
  },
  methods: {
    async getBuildingList() {
      const res = await getBuildingListAPI({
        name: this.dataParams.name,
        page: this.dataParams.page,
        pageSize: this.dataParams.pageSize
      })
      console.log(res)
      this.tableData = res.data.rows
      this.total = res.data.total
    },
    formatStatus(row) {
      const MAP = {
        0: '租赁中',
        1: '空置中'
      }
      return MAP[row.status]
    },
    // 分页器页码切换
    pageChage(val) {
      this.dataParams.page = val
      this.getBuildingList()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.dataParams.pageSize = val
      this.getBuildingList()
    },
    serchList() {
      this.dataParams.page = 1
      this.getBuildingList()
    },
    // 表格导出
    async exportToExcel() {
      const res = await getBuildingListAPI(this.dataParams)
      const tableHeader = ['name', 'floors', 'area', 'propertyFeePrice', 'status']
      // 处理数据保证
      const sheetData = res.data.rows.map(item => {
        const obj = {}
        tableHeader.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })
      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      // 创建一个新的工作簿
      const workbook = utils.book_new()
      // 把工作表添加到工作簿
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [['楼宇名称', '层数', '在管面积(㎡)', '物业费(㎡)', '状态']], { origin: 'A1' })
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    },
    // 添加楼宇
    // 适配新增和编辑模式
    confirmAdd() {
      this.$refs.addForm.validate(async(valid) => {
        if (valid) {
          if (this.addForm.id) {
            this.title = '编辑楼宇'
            await editBuildingListAPI(this.addForm)
            this.dialogVisible = false
          } else {
            this.title = '添加楼宇'
            // 1. 提交接口
            await createBuildingListAPI(this.addForm)
            this.resetFrom()
          }
          // 2. 获取列表
          this.getBuildingList()
          // 3. 关闭弹框
          this.showDialog = false
        }
      })
    },
    // 编辑楼宇
    async editBuilding(id) {
      console.log(id)
      this.showDialog = true
      this.title = '编辑楼宇'
      const { data: { name, floors, area, propertyFeePrice }} = await getBuildingDetailAPI(id)
      // console.log(data)
      this.addForm = { name, floors, area, propertyFeePrice, id }
    },
    delBuliding(id) {
      this.$confirm('此操作将永久删除该楼宇, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await deleteBuildingAPI(id)
        // console.log(res)
        if (res.code === 10000) {
          this.$message.success('删除成功！')
          this.serchList()
        } else {
          this.$message.error('删除失败！' + res.msg)
        }
      })
    },
    // 清空表单
    resetFrom() {
      this.addForm = {
        name: '',
        floors: null,
        area: null,
        propertyFeePrice: null
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;
  .search-main {
    width: 220px;
    margin-right: 10px;
  }
  .search-btn{
    margin-left:20px;
  }
}
.create-container{
  margin: 10px 0px;
}
.page-container{
  padding:4px 0px;
  text-align: right;
}
.form-container{
  padding:0px 80px;
}
</style>
